package com.kmzx.one.project.service.impl;

import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.entity.UserLogger;
import com.kmzx.one.project.entity.WxUser;
import com.kmzx.one.project.mapper.UserLoggerMapper;
import com.kmzx.one.project.mapper.WxUserMapper;
import com.kmzx.one.project.service.UserLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Project one
 * @Author: carol
 * @Date: 2020/5/22-10:33
 */
@Component
public class UserLogServiceImpl implements UserLogService {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserLoggerMapper userLoggerMapper;


    @Autowired
    WxUserMapper wxUserMapper;

    @Async
    @Override
    public void asyncInsertLoggerUser(UserLogger userLogger) {
        userLogger.setId(UUIDGenerator.generate());
        String userAgent = userLogger.getUserAgent();


        if (userAgent != null) {
            if (userAgent.indexOf('(') != -1) {
                int start = userAgent.indexOf("(");
                int end = userAgent.indexOf(")");
                String type = userAgent.substring(start + 1, end);
                userLogger.setDeviceType(type);
            } else {
                userLogger.setDeviceType(userAgent);
            }
        }

        userLogger.setLoginTime(new Date());
        int hashCode = userLogger.hashCode();
        logger.info("{},新增用户浏览记录,{}", hashCode, userLogger);
        String userId = userLogger.getUserId();
        if (userId != null && userId.length() > 3) {
            int position = userLogger.getPosition();
            if(position!=-1){
                WxUser wxUser = wxUserMapper.selectById(userId);
                if(wxUser!=null){
                    if (userLogger.getUnionId() == null) {
                        userLogger.setUnionId(wxUser.getUnionId());
                    }
                }
                userLoggerMapper.insertUserLogger(userLogger);
                logger.info("{},新增用户浏览记录,OK", hashCode);
            }else {
                logger.info("{},非必记录信息,缓存用户浏览记录,OK", hashCode);
            }
        }
    }
}
